package org.guegan.util.dircompare.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.guegan.util.dircompare.bean.DirBean;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class DirUtil {
	private static final String BEAN_NAME = "DirUtil";
	
	private Map<String, DirBean> repo = new HashMap<String, DirBean>();
	
	public static DirUtil getInstance() {
		return Factory.getBean(BEAN_NAME);
	}

	public DirBean getDir(File dir, Session session) {
		DirBean ret = null; 
		if (dir != null) {
			ret = repo.get(dir.getAbsolutePath());
			if (ret == null) {
				DirBean parent = getDir(dir.getParentFile(), session);
				String name = dir.getName();
				if (name.length() == 0) {
					name = dir.getAbsolutePath();
				}
				Criteria crit = session.createCriteria(DirBean.class);
				crit.add(parent == null ? Restrictions.isNull("parent") : Restrictions.eq("parent", parent));
				crit.add(Restrictions.eq("name", name));
				ret = (DirBean) crit.uniqueResult();
				if (ret == null) {
					ret = new DirBean();
					ret.setName(name);
					ret.setParent(parent);
					session.save(ret);
				}
				if (ret != null) {
					repo.put(dir.getAbsolutePath(), ret);
				}
			}

			if (ret != null && ret.getId() != null) {
				ret = (DirBean) session.get(DirBean.class, ret.getId());
			}
		}
		return ret;
	}

}
